package com.njcb.ams.factory.domain;

import com.njcb.ams.factory.comm.AmsComponent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组件上下文
 *
 * @author liuyanlong
 */
public class ComponentContext {
    /**
     * 组件上下文
     */
    private final Map<Class<? extends AmsComponent>, AmsComponent> componentObjects = new HashMap<Class<? extends AmsComponent>, AmsComponent>();

    /**
     * 共享对象
     */
    private final Map<Class<? extends Object>, Object> sharedObjects = new HashMap<Class<? extends Object>, Object>();

    private ComponentContext() {
    }

    private static ComponentContext singleton = null;

    public static synchronized ComponentContext getInstance() {
        if (singleton == null) {
            singleton = new ComponentContext();
        }
        return singleton;
    }

    public <C extends AmsComponent> void setComponentObject(Class<C> componentType, C object) {
        this.componentObjects.put(componentType, object);
    }

    public <S> void setSharedObject(Class<S> sharedType, S object) {
        this.sharedObjects.put(sharedType, object);
    }

    public <S> S getSharedObject(Class<S> sharedType) {
        return (S) this.sharedObjects.get(sharedType);
    }

    /**
     * 获取所有组件
     * @return 组件集合
     */
    public List<AmsComponent> getComponents(){
        List<AmsComponent> components = new ArrayList<AmsComponent>();
        for (AmsComponent component : componentObjects.values()) {
            components.add(component);
        }
        return components;
    }

}
